<template>
  <div id="space-manager-page">
    <a-flex justify="space-between">
      <h2>空间管理</h2>
      <a-space>
        <a-button type="primary" href="/add-space" target="_blank">+ 新增空间</a-button>
        <a-button type="primary" ghost href="/space-analyze?queryPublic=1" target="_blank"
          >分析公共图库
        </a-button>
        <a-button type="primary" href="/space-analyze?queryAll=1" target="_blank"
          >分析全空间
        </a-button>
      </a-space>
    </a-flex>
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="用户id" name="userId">
        <a-input
          v-model:value="searchParams.userId"
          placeholder="请输入用户id"
          allowClear
        ></a-input>
      </a-form-item>
      <a-form-item label="空间名称" name="spaceName">
        <a-input
          v-model:value="searchParams.spaceName"
          placeholder="请输入空间名称"
          allowClear
        ></a-input>
      </a-form-item>
      <a-form-item label="空间等级" name="spaceLevel">
        <a-select
          v-model:value="searchParams.spaceLevel"
          :options="SPACE_LEVEL_OPTIONS"
          style="min-width: 180px"
          placeholder="请选择空间等级"
          allowClear
        ></a-select>
      </a-form-item>
      <a-form-item label="空间类别" name="spaceType">
        <a-select
          v-model:value="searchParams.spaceType"
          :options="SPACE_TYPE_OPTIONS"
          style="min-width: 180px"
          placeholder="请选择空间类别"
          allowClear
        ></a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit"> 搜索</a-button>
      </a-form-item>
    </a-form>
    <div style="margin-bottom: 16px"></div>
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #headerCell="{ column }">
        <template v-if="column.key === 'name'">
          <span> Name </span>
        </template>
      </template>
      <template #bodyCell="{ column, record }">
        <!--空间级别-->
        <template v-if="column.dataIndex === 'spaceLevel'">
          <a-tag
            :color="
              record.spaceLevel === SPACE_LEVEL_ENUM.COMMON
                ? 'green'
                : SPACE_LEVEL_ENUM.PROFESSIONAL
                  ? 'blue'
                  : 'glod'
            "
          >
            {{ SPACE_LEVEL_MAP[record.spaceLevel] }}
          </a-tag>
        </template>
        <!--空间类型-->
        <template v-if="column.dataIndex === 'spaceType'">
          <a-tag :color="record.spaceType === SPACE_TYPE_ENUM.PRIVATE ? 'green' : 'blue'">
            {{ SPACE_TYPE_MAP[record.spaceType] }}
          </a-tag>
        </template>
        <!-- 使用情况 -->
        <template v-if="column.dataIndex === 'spaceUseInfo'">
          <div>大小：{{ formatSize(record.totalSize) }} / {{ formatSize(record.maxSize) }}</div>
          <div>数量：{{ record.totalCount }} / {{ record.maxCount }}</div>
        </template>
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.key === 'action'">
          <div class="button_box">
            <a-space wrap>
              <a-button type="link" :href="`/space-analyze?spaceId=${record.id}`"> 分析</a-button>
              <a-button type="link" :href="`/add-space?id=${record.id}`"> 编辑</a-button>
              <a-button type="link" danger @click="doDelete(record.id)">删除</a-button>
            </a-space>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  SPACE_LEVEL_ENUM,
  SPACE_LEVEL_MAP,
  SPACE_LEVEL_OPTIONS,
} from '@/constants/spaceConstant.ts'
import { formatSize } from '@/utils'
import { deleteSpaceUsingPost, listSpaceByPageUsingPost } from '@/request/api/spaceController.ts'
import {
  SPACE_TYPE_ENUM,
  SPACE_TYPE_MAP,
  SPACE_TYPE_OPTIONS,
} from '@/constants/spaceUserConstant.ts'

const searchParams = reactive<API.SpaceQueryRequest>({
  pageNum: 1,
  pageSize: 10,
  sortFields: ['createTime'],
  sortOrders: [0],
})

const total = ref(0)
const dataSource = ref<Array<API.Space>>([])

const pagination = computed(() => ({
  total: Number(total.value),
  current: searchParams.pageNum ?? 1,
  pageSize: searchParams.pageSize ?? 10,
  showSizeChanger: true,
  showTotal: (total: number) => `共${total}条`,
}))

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '空间名称',
    dataIndex: 'spaceName',
  },
  {
    title: '空间级别',
    dataIndex: 'spaceLevel',
  },
  {
    title: '空间类型',
    dataIndex: 'spaceType',
  },
  {
    title: '使用情况',
    dataIndex: 'spaceUseInfo',
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    width: 80,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 获取数据
const featureData = async () => {
  try {
    const { data: res } = await listSpaceByPageUsingPost({ ...searchParams })
    if (res?.code === 0 && res?.data) {
      total.value = res.data.total ?? 0
      dataSource.value = res.data.records ?? []
    } else {
      message.error(res?.message || '获取数据失败')
    }
  } catch (error) {
    message.error('获取数据失败')
    console.error(error)
  }
}
const handleTableChange = (pagination: any) => {
  // 表数据发生改变时
  searchParams.pageSize = pagination.pageSize
  searchParams.pageNum = pagination.current
  featureData()
}
const doSearch = () => {
  // 搜索
  searchParams.pageNum = 1
  featureData()
}
const doDelete = async (id: number) => {
  // 删除用户
  const { data: res } = await deleteSpaceUsingPost({ id: id })
  if (res.code == 0 && res.data) {
    message.success('删除成功')
    featureData()
  } else {
    message.error('删除失败')
  }
}
// 页面加载时调用
onMounted(() => {
  featureData()
})
</script>
<style lang="less" scoped></style>
